import React from 'react'
import './best-line-up.css'
import courtSrc from '../../res/images/web/vote/阵容／球场平面@2x.png'
import bannerSrc from "../../res/images/web/vote/活动模版／绿色2@2x.png";
import addSrc from "../../res/images/web/vote/btn／add@2x.png"
import {Modal, PickerView, Toast} from "antd-mobile";
import PopupLayout from "../game-room/components/Main/chat-room/PopupLayout/PopupLayout";
import CustomBotton from "../../shared-components/CustomButton/CustomBotton";
import {getVoteResultReq, voteBestLineupReq} from "../../apis/goApis";
import LocalStorageService from "../../utils/LocalStorageService";
import VoteGobackTab from "../GradePlayer/vote-goback-tab/vote-goback-tab";
import {Browser} from "../download/download";
import {searchParams} from "../mall/mall";
import {onTaskDone} from "../plan-detail/plan-detail";
import {test} from "../../utils/constants";
import {addLinkAndClick} from "../GradePlayer/GradePlayer";
const log = console.log.bind(console)
const selectData = [
    {
        label: '名字长长长长长长长长长长长长',
        value: '名字长长长长长长长长长长长长',
    },
    {
        label: '1',
        value: '1',
    },
    {
        label: '2',
        value: '2',
    },
]

export const checkAndGoBack = (history, url) => {
    const ios = Browser.version.ios
    const login = LocalStorageService.get('isLogin')
    if (login) {
        log('in')
        history && history.goBack()
        return
    }
    if (ios && url) {
        const params = searchParams()
        // let end = '../../../vote-list/line-up'
        let end = url
        if (params.webview === 'true') {
            end += '?'
            const ens = Object.entries(params)
            ens.map(([key, value], index) => {
                end += `${key}=${value}`
                if (index !== ens.length - 1) {
                    end += '&'
                }
            })
        }
        history && history.push(end)
    } else {
        history && history.goBack()
    }
}

class BestLineUp extends React.Component {
    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.voteId = parseInt(this.props.match.params.id)
        this.state = {
            position: '',
            modal: {
                select: false,
            },
            // select: ['0',],
            select: null,
            voted: false,
            event: '',
            playerOptions: [],
            selectData: [],
            selectIndex: 0,
            players: [
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
                '',
            ],
            bgFetchFinished: false,
            taskDone: false,
            taskInfo: '',
        }
    }

    componentDidMount() {
        const params = this.searchParams()
        const webview = params.webview
        if (webview === 'true') {
            log('webview')
            this.uid = params.uid
            this.setState({
                webview: true,
            }, () => this.detail())
        } else {
            this.detail()
        }
    }

    searchParams = () => {
        const search = window.location.search
            .slice(1)
            .split('&')
            .map(keyValue => {
                return keyValue.split('=')
            })
            .reduce((acc, cur) => {
                acc[cur[0]] = cur[1]
                return acc
            }, {})
        return search
    }


    detail = () => {
        const params = {
            Uid: this.uid,
            Sid: parseInt(this.props.match.params.id),
            Flag: 2,
        }
        log(params)
        getVoteResultReq(params).then(res => {
            const data = res.data.ok
            log(data)
            if (data) {
                // Count: 4
                // Createt: 1614907915
                // Endt: 1614994309
                // Id: 8
                // Match: "西甲"
                // Option: (4) [Array(1), Array(1), Array(1), Array(1)]
                // Startt: 1614907909
                if (data.Uid) {
                    log('已投票')
                    this.setState({
                        voted: true,
                        players: data.Options,
                        event: data.Match,
                    }, () => this.more())
                } else {
                    this.setState({
                        event: data.Match,
                        playerOptions: data.Option,
                    })
                }

            }
        })
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    callSelectModal = (index) => {
        if (this.state.voted) {
            return
        }
        let optionIndex, position
        if (index >= 0 && index <= 2) {
            optionIndex = 0
            position = '前锋'
        } else if (index >= 3 && index <= 6) {
            optionIndex = 1
            position = '中场'
        } else if (index >= 7 && index <= 9) {
            optionIndex = 2
            position = '后卫'
        } else if (index === 10) {
            optionIndex = 3
            position = '守门员'
        }
        const options = this.state.playerOptions[optionIndex]
        const selectData = options
            .filter(player => !this.state.players.includes(player))
            .map(player => ({label: player, value: player}))

        this.setState({
            selectIndex: index,
            selectData: selectData,
            select: [selectData[0]?.value,],
            position,
        }, () => {
            this.callModal('select')
        })
    }

    onSelectChange = (value) => {
        this.setState({
            select: value,
        })
    }

    selectPlayer = () => {
        const index = this.state.selectIndex
        const select = this.state.select[0]
        const players = this.state.players
        players[index] = select
        this.setState({
            players: [...players,],
        }, () => this.cancelModal('select'))
    }

    submit = () => {
        // Uid    string   `binding:"required"`
        // Sid    int      `binding:"min=1"`
        // Option []string `binding:"len=11"`
        const players = this.state.players
        const params = {
            Uid: this.uid,
            Sid: this.voteId,
            Option: players,
        }
        if (players.every(name => name.length > 0)) {
            log(params)
            voteBestLineupReq(params)
                .then((res) => {
                    const data = res.data
                    if (data.ok) {
                        this.detail()
                        this.more()
                    }
                })
        }

    }

    success = () => {
        Modal.alert(
            '',
            <p style={{color: '#333', padding: '30px',}}>提交成功，请到任务中心领取奖励</p>
        )
    }

    done = () => {
        const uid = this.state.webview ? this.searchParams().uid : this.uid
        onTaskDone(uid, 'ltft')
            .then(data => {
                if (data.Code === 0) {
                    this.setState({
                        taskDone: true,
                        taskInfo: data.Msg,
                    })
                }
            })
    }

    more = () => {
        const webview = this.state.webview
        const end = test ? 'http://test.youtoball.com:8080/ren_wu' : 'http://www.youtoball.com:8080/ren_wu'
        const btnList = [
            {
                text: <span>下次再做</span>,
                onPress: () => {},
            },
            {
                // text: webview
                //     ? <span style={{color: '#FFA500',}}>去做任务</span>
                //     : <a href={end}><span style={{color: '#FFA500',}}>去做任务</span></a>,
                text: <span style={{color: '#FFA500',}}>去做任务</span>,
                onPress: webview
                    ? () => addLinkAndClick(end)
                    : () => this.props.history.push('../../../ren_wu'),
            },
        ]
        Modal.alert(
            <span
                style={{
                    fontSize: '16px',
                    fontWeight: 500,
                    color: '#333333',
                    lineHeight: '22px',
                }}
            >'完成每日任务，可获得更多球星红包和奖励</span>,
            '合成球星越多，收益越多',
            btnList
        )
    }

    render() {

        const selectPlayerPickerPopup = <Modal
            visible={this.state.modal.select}
            animationType="slide-up"
            popup
            transparent
            onClose={() => this.cancelModal('select')}
        >
            <p style={{color: '#333',}}>
                选择{this.state.position}
            </p>
            <PickerView
                data={this.state.selectData}
                value={this.state.select}
                cascade={false}
                onChange={this.onSelectChange}
            />
            <div className='flex-space-between'>
                <CustomBotton
                    onClick={() => this.cancelModal('select')}
                    bg='#fff'
                    color='#333'
                    extrastyle={{
                        marginRight: '4px',
                        border: '2px solid #F8F8F8',
                    }}
                >
                    取消
                </CustomBotton>
                <CustomBotton
                    bg='#FFA500'
                    color='#fff'
                    onClick={() => this.selectPlayer()}
                >
                    确定
                </CustomBotton>
            </div>
        </Modal>
        const selectButtons = this.state.players.map((player, index) => {
            const positions = [
                {
                    top: '38px',
                    left: '16px',
                },
                {
                    top: '38px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                },
                {
                    top: '38px',
                    right: '16px',
                },
                {
                    top: '50%',
                    left: '16px',
                    transform: 'translateY(-300%)'
                },
                {
                    top: '50%',
                    right: '16px',
                    transform: 'translateY(-300%)',
                },
                {
                    top: '50%',
                    left: '50%',
                    transform: 'translate(-120%, -150%)',
                },
                {
                    top: '50%',
                    right: '50%',
                    transform: 'translate(120%, -150%)',
                },
                {
                    bottom: '50%',
                    left: '16px',
                    transform: 'translateY(200%)'
                },
                {
                    bottom: '50%',
                    left: '50%',
                    transform: 'translate(-50%, 200%)'
                },
                {
                    bottom: '50%',
                    right: '16px',
                    transform: 'translateY(200%)'
                },
                {
                    bottom: '80px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                },
            ]
            let title
            if (index >= 0 && index <=2) {
                title = '选择前锋'
            } else if (index >=3 && index <= 6) {
                title = '选择中场'
            } else if (index >= 7 && index <= 9) {
                title = '选择后卫'
            } else if (index === 10) {
                title = '选择门将'
            }
            const playerName = this.state.players[index]
            const selected = playerName.length > 0
            const selectPlayerButton = <div
                key={index}
                className='fade-in'
                style={{
                    ...positions[index],
                    position: 'absolute'
                }}
            >
                <div
                    className='select-player-button'
                    onClick={() => this.callSelectModal(index)}
                    // onClick={() => this.callModal('select')}
                >
                    {selected ? <p style={{color: '#333'}}>{playerName}</p> : <p>{title}</p>}
                    {this.state.voted === false && <img
                        src={addSrc}
                        className='select-player-button-add'
                        alt=""
                    />}
                </div>
            </div>
            return selectPlayerButton
        })
        const isAllSelected = this.state.players.every(p => p.length > 0)
        return <>
            {selectPlayerPickerPopup}
            <div
                className='grade-container best-line-up-container'
            >
                <VoteGobackTab
                    title='最佳阵容'
                    goBack={() => checkAndGoBack(this.props.history, '../../../vote-list/line-up')}
                    color='#fff'
                />
                <img src={bannerSrc} alt='' style={{width: '100%',}}/>
                <div className='best-line-up-players-container'>
                    {this.state.bgFetchFinished && <div className='best-line-up-players-event fade-in'>
                        <p>{this.state.event}</p>
                    </div>}
                    <img
                        src={courtSrc}
                        alt=''
                        style={{
                            width: '100%',
                        }}
                        onLoad={() => {
                            this.setState({
                                bgFetchFinished: true,
                            })
                        }}
                    />
                    {this.state.bgFetchFinished && selectButtons}
                </div>
                {this.state.bgFetchFinished && this.state.voted === false && <div className='grade-player-button fade-in'>
                    <CustomBotton
                        color={isAllSelected ? '#fff' : 'rgba(51, 51, 51, 0.4)'}
                        bg={isAllSelected ? '#FFA500' : '#E6E6E6'}
                        onClick={this.submit}
                    >
                        提交
                    </CustomBotton>
                </div>}
            </div>
        </>
    }
}

export default BestLineUp